<template>
  <div>
    <el-upload
      action="/api/v1/upload/picture"
      :on-exceed="handleExceed"
      :data="uploadParams"
      ref="upload"
      drag
      :list-type="'picture-card'"
      :http-request="handleUpload"
      :before-upload="beforeUpload"
      :file-list="fileList"
    >
      <i class="el-icon-plus"></i>
      <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <i class="el-icon-download"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="imgUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { calculateSHA512 } from '@/utils/encrypt'
import {
  uploadMusicScoreToCos,
  deleteMultipleUploadFile,
  deleteUploadFile
} from '@/api/cos'
import { getAccessToken } from '@/utils/auth'
import md5 from 'md5'
export default {
  props: {
    referenced_urls: {
      type: Array,
      required: false
    }
  },
  watch: {
    referenced_urls: {
      immediate: true,
      handler(val) {
        // 如果传递了url
        if (val) {
          // 清空fileList
          this.fileList = []
          this.imgList = val
          this.fileList = val.map(item => {
            return {
              name: `edited-image${item}`,
              url: item
            }
          })
        }
      }
    }
  },
  data() {
    return {
      fileList: [],
      imgUrl: '',
      uploadParams: {
        img: null
      },
      dialogVisible: false,
      disabled: false,
      currentFile: null,
      imgList: [],
      prefix: ''
    }
  },
  computed: {},
  mounted() {
    this.$nextTick(() => {
      // 监视发布事件
      this.$bus.$on('handleConfirm', this.SetImgList)
      this.$bus.$on('RemoveAlreadyUploadImage', this.RemoveAlreadyUploadImage)
      this.prefix =
        md5(new Date().toString().slice(1, 10)) +
        Math.floor(Math.random() * 3).toString()
    })
  },
  methods: {
    // 设置图片列表
    SetImgList() {
      console.log('handleConfirm', this.imgList)
      this.$store.commit('upload/SETIMGLIST', this.imgList)
      this.$store.commit('upload/SETFILEHASH', this.prefix)
    },
    handleExceed(files, fileList) {
      console.log('超出限制')
      // 文件数量超过限制的回调函数
      this.$message.warning(`只能上传 ${this.limit} 个文件`)
    },
    async handleRemove(file) {
      console.log(file)
      // cos清空数据
      const index = this.fileList.indexOf(file)
      console.log(index, this.imgList[index])

      if (index !== -1) {
        // 整理数据
        const formData = new FormData()
        formData.append('url', this.imgList[index])
        // 检测是否可以删除
        const res = await this.$API.upload.DetectCosRemove(formData)
        if (res.status == 200) {
          // 删除多余图片
          console.log('file.name', file.name)
          const response = await deleteUploadFile(
            'musicScore/' + this.prefix + '/' + file.name
          )
          if (response.statusCode == 200 || response.statusCode == 204) {
            this.fileList.splice(index, 1)
            this.imgList.splice(index, 1)
          }
        }
        // 如果其他资源引用了
        else if (res.status == 422) {
          this.fileList.splice(index, 1)

          this.imgList.splice(index, 1)
        }
      }
      // 本地清空数据
      // const index = this.fileList.indexOf(file);
      // console.log(index, this.imgList[index])

      // if (index !== -1) {
      //   // 整理数据
      //   const formData = new FormData()
      //   formData.append('url', this.imgList[index])
      //   // 删除多余图片
      //   const res = await this.$API.upload.DeleteAlreadyUploadFile(formData)
      //   if (res.status == 200 || res.status == 422) {
      //     this.fileList.splice(index, 1);

      //     this.imgList.splice(index, 1);

      //   }
      // }
    },
    // 放大缩略图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      console.log(file)
    },
    async handleUpload() {
      console.log('file', this.currentFile)
      // 格式校验
      const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
      const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif']

      const fileExtension = this.currentFile.name
        .substring(this.currentFile.name.lastIndexOf('.'))
        .toLowerCase()
      const fileMimeType = this.currentFile.type
      // 检查文件扩展名
      if (!allowedExtensions.includes(fileExtension)) {
        this.$message.error('只能上传 JPG、JPEG、PNG 或 GIF 格式的图片')
        this.fileList = []
        return
      }

      // 检查文件 MIME 类型
      if (!allowedMimeTypes.includes(fileMimeType)) {
        this.$message.error('只能上传 JPG、JPEG、PNG 或 GIF 格式的图片')
        this.fileList = []
        return
      }
      // cos对象存储
      try {
        const response = await uploadMusicScoreToCos(
          this.currentFile,
          this.currentFile.name,
          this.prefix
        )
        console.log(response)
        let img_url = 'http://' + response.Location
        // 上传成功后将 URL 存储到 Vuex 中
        this.$store.commit('upload/SETIMGURL', img_url)
        // 上传成功后将文件添加到 fileList 中
        this.fileList.push({
          name: this.currentFile.name,
          url: img_url
        })
        this.imgList.push(img_url)
        // 清空当前文件
        this.currentFile = null
      } catch (error) {
        console.error(error)
        this.$message.error('上传失败')
      }
      // 本地存储
      // const fileReader = new FileReader()
      // // 以8192字节的形式读取文件
      // const chunkSize = 8192;
      // let currentByte = 0;
      // // 文件读取
      // fileReader.onload = async () => {
      //   const arrayBuffer = fileReader.result;
      //   const uint8Array = new Uint8Array(arrayBuffer);
      //   // 格式转换
      //   const fileBlob = new Blob([arrayBuffer], { type: this.currentFile.type });
      //   // 生成hash值
      //   const file_hash = await calculateSHA512(fileBlob);
      //   const datas = this.$qs.stringify({ file_hash })
      //   console.log(file_hash, datas)
      //   try {
      //     // 验证文件是否存在
      //     const res = await this.$API.upload.CheckExist(datas)
      //     console.log(res)
      //     // 发起监听窗口关闭事件
      //     this.$bus.$on("RemoveAlreadyUploadImage", this.RemoveAlreadyUploadImage)
      //     // 如果存在秒传地址
      //     if (res && res.status == 200) {
      //       this.imgList.push(res.data.url)
      //       // this.videoUrl = res.data.url
      //       // this.$store.commit("upload/SETIMGURL", res.data.url)
      //       // console.log('imgurl', this.$store.state.upload.img_url)
      //       return;
      //     }
      //     // 整理数据
      //     // const formData = new FormData()
      //     formData.append('img', this.currentFile)
      //     // 上传图片
      //     const response = await this.$API.upload.uploadImage(formData)
      //     console.log(response)
      //     if (response.status == 200) {
      //       // this.fileList.push(this.currentFile)
      //       this.imgList.push(response.data.url)

      //       // 数据传递
      //       // this.$store.commit("upload/SETIMGURL", res.data.url)

      //     }
      //   } catch (error) {
      //     this.$message.error("文件检查请求失败")
      //     return;
      //   }
      // }
      // fileReader.readAsArrayBuffer(this.currentFile);
    },
    async beforeUpload(file) {
      console.log(file)
      this.currentFile = file
      // 阻止自动上传
      return false
    },
    // 移除多余的图片
    async RemoveAlreadyUploadImage() {
      if (!this.imgList) return
      // cos批量删除
      // 检查关联性
      let formData = new FormData()
      for (let i = 0; i < this.imgList.length; i++) {
        formData.append('urls[]', this.imgList[i])
      }
      const res = await this.$API.upload.DetectCosBatchRemove(formData)
      console.log(res)
      // 有资源引用了该图片需要删除
      if (res.status == 200) {
        // 整理数据
        const datas = this.fileList.map(item => {
          return {
            Key: item.name
          }
        })
        const response = await deleteMultipleUploadFile(datas)
        console.log('removbe', response)
        if (response.statusCode == 200) {
          // 清空数据
          this.fileList = []
          this.imgList = []
          this.prefix = ''
        }
      }
      // 有资源引用不必删除
      else if (res.status == 422) {
        return
      }
      // 本地批量删除
      // const formData = new FormData()
      // console.log('remove', this.imgList)
      // for (let i = 0; i < this.imgList.length; i++) {
      //   formData.append("urls[]", this.imgList[i])

      // }

      // const res = await this.$API.upload.BatchDeleteAlreadyUploadFile(formData)
      // if (res.status == 200 || res.status == 422) {
      //   // 初始化数据
      //   this.imgList = []
      //   this.fileList = []
      // }
    }
  }
}
</script>
